package com.zjh.photoshopstudy.app.upload;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.design.widget.TabLayout;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.text.util.Linkify;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.dueeeke.videocontroller.StandardVideoController;
import com.dueeeke.videocontroller.component.VodControlView;
import com.dueeeke.videoplayer.player.VideoView;
import com.zjh.photoshopstudy.Model.VideoEntity;
import com.zjh.photoshopstudy.R;
import com.zjh.photoshopstudy.Utils.CommentImageClick;
import com.zjh.photoshopstudy.Utils.Data;
import com.zjh.photoshopstudy.Utils.LinkClick;
import com.zjh.photoshopstudy.app.video.ImageActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static com.zjh.photoshopstudy.app.download.DownloadAdapter.showOpenTypeDialog;

public class UploadActivity extends AppCompatActivity {
    private Uri uri;
    private VideoView mVideoView;
    private TextView image;
    private TextView materia;
    private TabLayout mTypeLayout;
    private TabLayout mLevelLayout;
    private boolean isSelected = false;
    private Uri imageUri;
    private Uri materiaUri;
    private String materiaPath;
    private List<Uri> uriList = new ArrayList<>();
    private List<Uri> linkList = new ArrayList<>();
    private EditText resumeEdit;
    private EditText titleEdit;
    private int current;
    UploadPresent mPresent;

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        isSelected = true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload);
        mPresent = new UploadPresent(this);
        if (!isSelected) {
            initVideo();
        }
    }

    public void initVideo() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("video/*");
        startActivityForResult(intent, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
            isSelected = true;
            uri = data.getData();
            initPlayer();
            initView();
        } else if (requestCode == 2 && resultCode == Activity.RESULT_OK) {
            imageUri = data.getData();
            image.setVisibility(View.VISIBLE);
        } else if (requestCode == 3 && resultCode == Activity.RESULT_OK) {
            addResume(data.getData(), "查看图片 ");
            updateResumeEdit();
        } else if (requestCode == 4 && resultCode == Activity.RESULT_OK) {
            String docId = DocumentsContract.getDocumentId(data.getData());
            String[] split = docId.split(":");
            String type = split[0];
            materiaUri = Uri.parse("file://" + Environment.getExternalStorageDirectory() + "/" + split[1]);
            materia.setVisibility(View.VISIBLE);
        } else if (!isSelected) {
            finish();
        }
    }

    private void addResume(Uri data, String s) {
        resumeEdit.requestFocus();
        String text = resumeEdit.getText().toString();
        current = resumeEdit.getSelectionStart();
        int index = 0;
        if (current == -1) {
            current++;
        }
        String pre = text.substring(0, current);
        String next = text.substring(current);
        text = pre + s + next;
        String temp = text;
        int count = 0;
        while (temp.contains(s)) {
            int i = temp.indexOf(s);
            count += i;
            if (current <= count) {
                if (s.equals("查看图片 ")) {
                    uriList.add(index, data);
                } else {
                    linkList.add(index, data);
                }
                break;
            }
            index++;
            count += s.length();
            temp = temp.substring(i + s.length());
        }
        resumeEdit.setText(text);
    }

    private void initView() {
        mTypeLayout = findViewById(R.id.type);
        mLevelLayout = findViewById(R.id.level);
        image = findViewById(R.id.image_uri);
        materia = findViewById(R.id.materia_uri);
        titleEdit = findViewById(R.id.title);
        resumeEdit = findViewById(R.id.resume);
        resumeEdit.setMovementMethod(LinkMovementMethod.getInstance());
        for (int i = 1; i < Data.TYPES.length; i++) {
            mTypeLayout.addTab(mTypeLayout.newTab().setText(Data.TYPES[i]));
        }
        for (int i = 1; i < Data.LEVELS.length; i++) {
            mLevelLayout.addTab(mLevelLayout.newTab().setText(Data.LEVELS[i]));
        }
        resumeEdit.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int i, KeyEvent keyEvent) {
                if (i == KeyEvent.KEYCODE_DEL) {
                    EditText editText = ((EditText) view);
                    String text = editText.getText().toString();
                    int curr = editText.getSelectionStart();
                    if (curr < 0) {
                        return false;
                    }
                    String newText = subString(text, "查看图片 ", curr);
                    newText = subString(newText, "打开链接 ", curr);
                    SpannableStringBuilder spannable = new SpannableStringBuilder(newText);
                    addSpanable(newText, "查看图片 ", spannable);
                    addSpanable(newText, "打开链接 ", spannable);
                    resumeEdit.setText(spannable);
                    if (!newText.equals(text) && curr - 4 >= 0 && curr - 4 <= resumeEdit.getText().toString().length())
                        resumeEdit.setSelection(curr - 4);
                    else resumeEdit.setSelection(curr);
                }
                return false;
            }
        });
    }

    private String subString(String text, String s, int curr) {
        if (curr > text.length()) {
            return text;
        }
        String temp = text.substring(0, curr);
        String newText = text;
        if (temp.endsWith(s)) {
            int index = -1;
            do {
                index++;
                temp = temp.substring(0, temp.lastIndexOf(s));
            } while (temp.contains(s));
            if (s.equals("查看图片 ")) {
                uriList.remove(index);
            } else {
                linkList.remove(index);
            }
            int c = curr - s.length() + 1;
            newText = text.substring(0, c) + text.substring(curr);
        }
        return newText;
    }

    private void initPlayer() {
        mVideoView = findViewById(R.id.player);
        mVideoView.setUrl(uri.toString()); //设置视频地址
        StandardVideoController controller = new StandardVideoController(this);
        VodControlView vodControlView = new VodControlView(this);//点播控制条
        controller.addControlComponent(vodControlView);
        mVideoView.setVideoController(controller); //设置控制器
        mVideoView.setLooping(true);
        mVideoView.start();
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.image_uri:
                openImage();
                break;
            case R.id.video_image:
                selectVideoImage();
                break;
            case R.id.link:
                openDialog();
                break;
            case R.id.image:
                selectContentImage();
                break;
            case R.id.upload_btn:
                upload();
                break;
            case R.id.materia:
                selectMateria();
                break;
            case R.id.materia_uri:
                openMateria();
                break;
        }
    }

    private void upload() {
        if (imageUri == null) {
            Toast.makeText(this, "请选择视频封面", Toast.LENGTH_SHORT).show();
            selectVideoImage();
        } else if (materiaUri == null) {
            Toast.makeText(this, "请选择素材", Toast.LENGTH_SHORT).show();
            selectMateria();
        } else if (titleEdit.getText().toString().trim().isEmpty()) {
            Toast.makeText(this, "请输入标题", Toast.LENGTH_SHORT).show();
            titleEdit.requestFocus();
        } else if (resumeEdit.getText().toString().trim().isEmpty()) {
            Toast.makeText(this, "请输入简介", Toast.LENGTH_SHORT).show();
            resumeEdit.requestFocus();
        } else {
            String title = titleEdit.getText().toString();
            String resume = resumeEdit.getText().toString();
            int type = mTypeLayout.getSelectedTabPosition() + 1;
            int level = mLevelLayout.getSelectedTabPosition() + 1;
            VideoEntity videoEntity = new VideoEntity();
            videoEntity.setvTitle(title);
            videoEntity.setvContent(resume);
            videoEntity.setvType(type);
            videoEntity.setvLevel(level);
            videoEntity.setvThumbnailPath(imageUri.toString());
            uriList.add(0, materiaUri);
            uriList.add(0, imageUri);
            uriList.add(0, uri);
            mPresent.upload(videoEntity, uriList, linkList);
            Toast.makeText(this, "开始上传", Toast.LENGTH_SHORT).show();
            finish();
        }


    }

    private void openDialog() {
        final EditText et = new EditText(this);
        new AlertDialog.Builder(this).setTitle("请输入网址")
                .setView(et)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (!Linkify.addLinks(et, Linkify.WEB_URLS)) {
                            Toast.makeText(getApplicationContext(), "请输入正确的网址", Toast.LENGTH_LONG).show();
                        } else {
                            addResume(Uri.parse(et.getText().toString()), "打开链接 ");
                            updateResumeEdit();
                        }
                    }
                }).setNegativeButton("取消", null).show();

    }

    private void updateResumeEdit() {
        String text = resumeEdit.getText().toString();
        SpannableStringBuilder spannable = new SpannableStringBuilder(text);
        addSpanable(text, "查看图片 ", spannable);
        addSpanable(text, "打开链接 ", spannable);
        resumeEdit.setText(spannable);
        resumeEdit.setSelection(current + 5);
    }

    private void addSpanable(String temp, String s, SpannableStringBuilder spannable) {
        int current = 0;
        int index = 0;
        while (temp.contains(s)) {
            int i = temp.indexOf(s);
            int start = i + current;
            int end = start + s.length();
            if (s.equals("查看图片 ")) {
                CommentImageClick clickableSpan = new CommentImageClick(this, uriList.get(index).toString());
                spannable.setSpan(clickableSpan, start, end - 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
            } else {
                LinkClick clickableSpan = new LinkClick(this, linkList.get(index).toString());
                spannable.setSpan(clickableSpan, start, end - 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
            }
            ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.parseColor("#FF00B8D4"));
            spannable.setSpan(colorSpan, start, end - 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
            current = end;
            temp = temp.substring(i + s.length());
            index++;
        }
    }

    private void selectContentImage() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        Intent chooser = Intent.createChooser(intent, "选择图片");
        startActivityForResult(chooser, 3);
    }

    private void openImage() {
        Intent intent = new Intent(this, ImageActivity.class);
        intent.putExtra("imageUrl", imageUri.toString());
        startActivity(intent);
    }

    private void selectVideoImage() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        Intent chooser = Intent.createChooser(intent, "选择图片");
        startActivityForResult(chooser, 2);
    }

    private void openMateria() {
        String filePath = materiaUri.getPath();
        Uri uri = Uri.parse("file://" + filePath);
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        String type = getMIMEType(filePath);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            uri = FileProvider.getUriForFile(this, "com.zjh.photoshopstudy.fileprovider", new File(filePath));
        }
        intent.setDataAndType(uri, type);
        if (!type.equals("*/*")) {
            startActivity(intent);
        } else {
            startActivity(showOpenTypeDialog(filePath));
        }
    }

    private void selectMateria() {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("*/*");
        intent.putExtra(Intent.EXTRA_MIME_TYPES, new String[]{"application/zip", "application/x-rar-compressed"});
        startActivityForResult(intent, 4);
    }

    public static String getMIMEType(String filePath) {
        String type = "*/*";
        String fName = filePath;

        int dotIndex = fName.lastIndexOf(".");
        if (dotIndex < 0) {
            return type;
        }

        String end = fName.substring(dotIndex, fName.length()).toLowerCase();
        if (end == "") {
            return type;
        }

        for (int i = 0; i < Data.MIME_MapTable.length; i++) {
            if (end.equals(Data.MIME_MapTable[i][0])) {
                type = Data.MIME_MapTable[i][1];
            }
        }
        return type;
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mVideoView != null)
            mVideoView.pause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mVideoView != null)
            mVideoView.resume();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mVideoView != null)
            mVideoView.release();
    }


    @Override
    public void onBackPressed() {
        if (mVideoView != null && !mVideoView.onBackPressed()) {
            super.onBackPressed();
        }
    }

}
